package com.test.util;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import magick.CompositeOperator;
import magick.DrawInfo;
import magick.ImageInfo;
import magick.MagickException;
import magick.MagickImage;
import magick.PixelPacket;

import org.apache.log4j.Logger;

/**
 * ImageMagick <br>
 * 图片处理工具类
 * <p>
 * Copyright: Copyright (c) Jul 29, 2011 9:54:55 AM
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: liuxl@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */

public class ImageMagick {

	public static final Logger log = Logger.getLogger(ImageMagick.class);

	static {
		// 不能漏掉这个，不然jmagick.jar的路径找不到
		System.setProperty("jmagick.systemclassloader", "no");
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(System.getProperty("os.name"));
		scaleImage("F:/cplatform_workspace/cplatformCMS/WebContent/upload/2011/07/30/1311989040500.jpg",
		           "F:/cplatform_workspace/cplatformCMS/WebContent/upload/2011/07/30/1311989040500-new.jpg", 50, 100);
		/*
		 * wordWatermark("E:\\pic\\42869.jpg", "啊啊啊啊啊aaaa", "e:\\pic\\aa.jpg");
		 * picWatermark("E:\\pic\\42869.jpg", "E:\\pic\\11.jpg",
		 * "E:\\pic\\picwater.jpg"); rectangle("E:\\pic\\42869.jpg",
		 * "E:\\pic\\22.jpg", 200, 250, 0, 0);
		 */
	}

	/**
	 * 添加图片水印
	 * 
	 * @param filePath
	 *            源文件路径
	 * @param waterMarkPath
	 *            水印图片路径
	 * @param toPath
	 *            生成图片路径
	 */
	public static void picWatermark(String filePath, String waterMarkPath, String toPath) {
		MagickImage image = null;
		MagickImage logimg = null;

		try {
			Image fileImg = ImageIO.read(new File(filePath));
			Image waterImg = ImageIO.read(new File(waterMarkPath));

			int fileWidth = fileImg.getWidth(null);
			int fileHeight = fileImg.getHeight(null);
			int waterWidth = waterImg.getWidth(null);
			int waterHeight = waterImg.getHeight(null);

			ImageInfo info = new ImageInfo(filePath);
			ImageInfo logo = new ImageInfo(waterMarkPath);
			image = new MagickImage(info);
			logimg = new MagickImage(logo);

			image.compositeImage(CompositeOperator.AtopCompositeOp, logimg, fileWidth - waterWidth, fileHeight - waterHeight);
			image.setFileName(toPath);
			image.writeImage(info);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (MagickException e) {
			e.printStackTrace();
		}
		finally {
			if (image != null) {
				image.destroyImages();
			}
			if (logimg != null) {
				logimg.destroyImages();
			}
		}
	}

	/**
	 * 剪裁图片
	 * 
	 * @param filePath
	 *            源文件地址
	 * @param toPath
	 *            生成图片地址
	 * @param left
	 *            剪裁距离左侧 距离
	 * @param top
	 *            剪裁距离上面 距离
	 * @param right
	 *            剪裁 从左侧起始位置向右延伸长度 如果为0 则是不限制
	 * @param bottom
	 *            剪裁 从上侧起始位置向下延伸长度 如果为0 则是不限制
	 */
	public static void rectangle(String filePath, String toPath, int left, int top, int right, int bottom) {
		MagickImage mi = null;
		MagickImage toMi = null;
		try {
			ImageInfo info = new ImageInfo(filePath);
			mi = new MagickImage(info);
			Rectangle rect = new Rectangle(left, top, right, bottom);
			toMi = mi.cropImage(rect);
			toMi.setFileName(toPath);
			toMi.writeImage(info);
		}
		catch (MagickException e) {
			e.printStackTrace();
		}
		finally {
			if (mi != null) {
				mi.destroyImages();
			}
			if (toMi != null) {
				toMi.destroyImages();
			}
		}
	}

	/**
	 * 压缩图片
	 * 
	 * @param filePath
	 *            源文件路径
	 * @param toPath
	 *            缩略图路径
	 */
	public static void scaleImage(String filePath, String toPath, Integer width, Integer height) {
		log.error(filePath + "=======" + toPath);

		File file = new File(filePath);

		if (file.exists()) {
			log.error("图片存在！");
		} else {
			log.error("图片不存在！");
		}

		ImageInfo info = null;
		MagickImage image = null;
		MagickImage scaled = null;
		Dimension imageDim = null;
		try {
			info = new ImageInfo(filePath);
			info.setQuality(70);
			image = new MagickImage(info);
			imageDim = image.getDimension();

			if (width == null) {
				if (height < imageDim.height) {
					scaled = image.scaleImage(height * imageDim.width / imageDim.height, height);// 小图片文件的大小.
				} else {
					scaled = image.scaleImage(imageDim.width, imageDim.height);
				}
			} else if (height == null) {
				if (width < imageDim.width) {
					scaled = image.scaleImage(width, width * imageDim.height / imageDim.width);// 小图片文件的大小.
				} else {
					scaled = image.scaleImage(imageDim.width, imageDim.height);
				}
			} else if (width == null && height == null) {
				scaled = image.scaleImage(100, 100);// 小图片文件的大小.
			} else {
				scaled = image.scaleImage(width, height);// 小图片文件的大小.

			}
			scaled.setFileName(toPath);
			scaled.writeImage(info);
		}
		catch (Exception e) {
			e.printStackTrace();
			log.error("scaleImage [Exception] errors . ", e);
		}
		finally {
			if (image != null) {
				image.destroyImages();
			}
			if (scaled != null) {
				scaled.destroyImages();
			}
		}
	}

	/**
	 * 添加文字水印
	 * 
	 * @param filePath
	 *            源文件路径
	 * @param text
	 *            水印文字
	 * @param toPath
	 *            生成图片路径
	 */
	public static void wordWatermark(String filePath, String text, String toPath) {
		try {
			ImageInfo info = new ImageInfo(filePath);

			MagickImage mimg = new MagickImage(info);
			DrawInfo aInfo = new DrawInfo(info);

			aInfo.setFill(PixelPacket.queryColorDatabase("green"));
			aInfo.setUnderColor(PixelPacket.queryColorDatabase("yellow"));
			aInfo.setOpacity(0);
			aInfo.setPointsize(20);

			// 注意这里解决中文字体问题，有以下两行才可正常显示
			/*
			 * String fontPath = "/home/user1/wmfont/simsun.ttf";
			 * aInfo.setFont(fontPath);
			 */

			String fontPath = "";

			if (System.getProperty("os.name").indexOf("Windows") == -1) {
				fontPath = "/home/user1/wmfont/simsun.ttf";
			} else {
				fontPath = "C:\\WINDOWS\\Fonts\\SIMSUN.TTC";
			}

			aInfo.setFont(fontPath);
			aInfo.setText(text);
			aInfo.setTextAntialias(true);
			aInfo.setGeometry("+0+20");
			// Step 4: Annotating
			mimg.annotateImage(aInfo);

			// Step 5: Writing the new file
			mimg.setFileName(toPath);
			mimg.writeImage(info);
			mimg.destroyImages();
			mimg = null;
		}
		catch (MagickException e) {
			e.printStackTrace();
		}
	}
}
